#!/usr/local/bin/python2.7
#-*-coding:utf-8 -*-
import requests
import sys
import json
import urllib3
import redis
from requests.packages.urllib3.exceptions import InsecureRequestWarning
import argparse


# 禁用安全请求警告
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
urllib3.disable_warnings()

r = redis.Redis(host='192.168.23.129', port=6379)
reload(sys)
sys.setdefaultencoding('utf-8')

parser = argparse.ArgumentParser(description='manual to this script')
parser.add_argument('--user', type=str, default=None)
parser.add_argument('--Content', type=str, default=None)
parser.add_argument('--title', type=str, default=None)
args = parser.parse_args()
User = args.user
Content = args.Content
title = args.title
if "Resolved" in title:
    Content = "<div class=\"blue\">%s</div>" % Content
else:
    Content = "<div class=\"red\">%s</div>" % Content

def GetToken(Corpid,Secret):
    Url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"
    Data = {
        "corpid":Corpid,
        "corpsecret":Secret
    }
    r = requests.get(url=Url,params=Data,verify=False)
    Token = r.json()['access_token']
    return Token

def read_redis_token():
    global Token
    if r.exists('weixin_token') == True:
        Token = r.get('weixin_token')
    elif r.exists('weixin_token') == False:
        Token = GetToken(Corpid,Secret)
        r.set('weixin_token', Token, 7200)
    return Token

def SendMessage(Token,User,Agentid,Content):
    Url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s" % Token
    Data = {
        "touser": User,
        "msgtype": "textcard",
        "agentid": Agentid,
	    "textcard" : {
            "title" : title,
            "description" : Content,
            "url" : "",
            "btntxt":"更多"
        }
    }
    r = requests.post(url=Url,data=json.dumps(Data),verify=False)
    return r.text


if __name__ == '__main__':
    Corpid = ""
    Secret = ""
    Agentid = ""
    Token = read_redis_token()
    Status = SendMessage(Token, User, Agentid, Content)
    print(Status)